package gw.com.android.ui.quote2.addquote;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.flyco.tablayout.SlidingTabLayout;
import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.chart.output.utils.GTTKDataManager;
import com.gwtsz.gts2.hx.R;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigTypesDeal;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.ViewPagerAdapter;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.OpenApi;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.dialog.DialogDismissedListener;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.view.CustomViewPager;

/**
 * Created by reeta.zou
 * 自选添加界面
 */
public class QuoteAddSelfActivity extends BaseActivity {

    //主载体
    @BindView(R.id.tabs)
    SlidingTabLayout mTabLayout;//滑动的头部

    @BindView(R.id.search_bar)
    View mSearchBar;
    @BindView(R.id.viewpager)
    CustomViewPager mViewPager;
    @BindView(R.id.loading_progress_view)
    View mLoadingProgressView;

    /**
     * 行情自选产品列表控件
     **/
    private DataItemResult mTabTitles;
    private ConfigTypesDeal mTypesDeal;
    private ViewPagerAdapter mAdapter;
    private HashMap<String, QuoteAddFragment> mFragmentList;
    private QuoteAddFragment mCurrentFragment = null; // 当前显示的fragment

    private String mCurType = GTSConst.ZONE_TYPE_FX + "";
    private QuoteSearchPopWindow searchPopWindow = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onSendQuote();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_quote_self_add;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this);
        mTitleBar.setAppTitle(AppMain.getAppString(R.string.quote_title_add_product));
    }

    @Override
    protected void initViewData() {
        if (ConfigUtil.instance().hasQuoteTypeFunction() == 1) {
            mSearchBar.setVisibility(View.VISIBLE);
        } else {
            mSearchBar.setVisibility(View.GONE);
        }
        mTypesDeal = new ConfigTypesDeal();
//        if (mTabTitles.getDataCount() > 0) {
//            setTabs();
//        }
        if (!ConfigUtil.instance().hasZoneDisplay()) {
            mTabLayout.setVisibility(View.GONE);
        }
        mFragmentList = new HashMap();


        //调用一下CPS开关，根据结果决定要不要显示 数字货币
        requestCpsSwitch();

    }

    private void requestCpsSwitch() {//加个特殊逻辑：发送请求去访问CPS接口，看看开关是否打开，如果打开，就显示数字货币；关闭，则不显示数字货币;
        mLoadingProgressView.setVisibility(View.VISIBLE);
        OpenApi.requestDigitalCurrency(new HttpCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean result) {
                mLoadingProgressView.setVisibility(View.GONE);
                loadQuoteTable(result);
            }

            @Override
            public void onFailure(Exception e) {
                mLoadingProgressView.setVisibility(View.GONE);
                loadQuoteTable(true);//多一事不如少一事，既然请求失败，那就不显示....囧,好吧，那还是显示
            }
        });
    }

    private void loadQuoteTable(final boolean ifCpsOpen) {
        if (ifCpsOpen) {//如果开关打开
            mTabTitles = mTypesDeal.getQuoteTypeList();//那就取全部类型
        } else {//如果开关关闭，就
            mTabTitles = mTypesDeal.getQuoteTypeListWithoutBtType();
        }

        if (mTabTitles.getItem(0) != null) {
            mCurType = mTabTitles.getItem(0).getString(ConfigType.CONFIG_TYPE_TYPE_TAG);
        }
        mCurrentFragment = QuoteAddFragment.newInstance(mCurType);
        mFragmentList.put(mCurType + "", mCurrentFragment);

        boolean if1 = ConfigUtil.instance().hasZoneDisplay();
        boolean if2 = mTabTitles.getDataCount() <= 1;

        if (!if1 || if2) {
            mTabLayout.setVisibility(View.GONE);
            mViewPager.setNoScroll(true);
        } else {
            mTabLayout.setVisibility(View.VISIBLE);
            mViewPager.setNoScroll(false);
        }

        mAdapter = new ViewPagerAdapter(mFragmentManager, mTabTitles, new ViewPagerAdapter.ShowFragmentListener() {
            @Override
            public PushMsgTabFragment showFragment(String type, int position) {
                return getFragment(type);
            }
        });
        mViewPager.setAdapter(mAdapter);
        mTabLayout.setViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Logger.e("MainQuoteFragment onPageSelected " + position);
                if (position >= 0 && position < mTabTitles.getDataCount()) {
                    DataItemDetail itemDetail = mTabTitles.getItem(position);
                    mCurType = itemDetail.getString(ConfigType.CONFIG_TYPE_TYPE_TAG);
                    mCurrentFragment = getFragment(mCurType);
//                    mCurrentFragment.refreshViewData();
                    onSendQuote();
                    MobclickEventUtlis.MobclickEventByAccountType(QuoteAddSelfActivity.this, "Clicksection");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

//    /**
//     * 显示指定tab
//     */
//    public void setTabs() {
//        for (int i = 0; i < mTabTitles.getDataCount(); i++) {
//            TabLayout.Tab tab1 = mTabLayout.newTab().setText(mTabTitles.getItem(i).getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
//            mTabLayout.addTab(tab1);
//        }
//    }

    /**
     * 返回当前显示的fragment界面
     */
    private QuoteAddFragment getFragment(String type) {
        if (mFragmentList.containsKey(type + "")) {
            Logger.e("MainQuoteFragment getFragment type " + type);
            return mFragmentList.get(type + "");
        } else {
            Logger.e("MainQuoteFragment getFragment type is new" + type);
            QuoteAddFragment fragment = QuoteAddFragment.newInstance(type);
            mFragmentList.put(type + "", fragment);
            return fragment;
        }
    }

    @Override
    public void registerRxBus() {
        super.registerRxBus();
        Disposable quoteAllRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_ALLLIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        onSymbolNotify();
                    }
                });

        bindSubscription(quoteAllRegister);

        Disposable quoteListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        onSymbolNotify();
                    }
                });

        bindSubscription(quoteListRegister);

        Disposable quoteUpdateRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        onSymbolNotify();
                    }
                });

        bindSubscription(quoteUpdateRegister);

        Disposable quoteTickRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_TICK_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        if (null != model) {
                            onSymbolNotify(model.getInt(GTSConst.JSON_KEY_CODEID));
                        }
                    }
                });

        bindSubscription(quoteTickRegister);
    }

    @OnClick(R.id.search_bar)
    void onSearchClik() {
        searchPopWindow = new QuoteSearchPopWindow(this, mTitleBar);
        searchPopWindow.setOnDismissedListener(new DialogDismissedListener() {
            @Override
            public void onDismissed() {
                if (null != mCurrentFragment) {
                    mCurrentFragment.refreshViewData();
                }
            }
        });
        searchPopWindow.show();
        MobclickEventUtlis.MobclickEventByAccountType(QuoteAddSelfActivity.this, "Loading");
    }

    @Override
    protected void onResume() {
        super.onResume();
        onSendQuote();
    }

    /**
     * 刷新ui
     */
    public void onSymbolNotify() {
        if (null != mCurrentFragment) {
            mCurrentFragment.refreshViewData();
            onSendQuote();
        }
    }

    /**
     * 刷新ui
     */
    public void onSymbolNotify(int codeId) {
        if (mCurrentFragment != null && mCurrentFragment.isResumed() && !mCurrentFragment.isHidden()) {
            mCurrentFragment.onSymbolNotify(codeId);
        }
    }

    protected void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCodes(mCurType));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //图表界面点击返回到主面板
        Logger.e("QuoteAddSelfActivity 图表界面返回到主面板 ");
        GTTKDataManager.instance().clearTimeData();
        GTTKDataManager.instance().clearKData();
        GTTKDataManager.instance().clearIndictor();
        AppTerminal.instance().clearAllChartCache();
        if (resultCode == AppContances.RESULT_CODE) {
            Logger.e("QuoteAddSelfActivity 交易界面直接返回到主面板 ");
            setResult(AppContances.RESULT_CODE);
            finish();
        }
    }
}
